#ifndef QHANDLER_H
#define QHANDLER_H

#include <QObject>
#include <QThread>
#include <QMap>
#include <QVariant>

struct QHandlerMessage;

/**
 * 仿安卓 Handler，通过该对象向一个后台线程发送消息，并在后台线程中处理这个消息
 */
class QHandler : public QObject
{
    Q_OBJECT
public:
    QHandler()
        : QObject(nullptr)
    {
        connect(this, SIGNAL(sendMessage_signal(QHandlerMessage*)),
                this, SLOT(onMessage(QHandlerMessage*)));
    }
    ~QHandler() Q_DECL_OVERRIDE;

    void stopBackgroundThread()
    {
        if (mWorker.isRunning())
        {
            mWorker.quit();
            mWorker.wait();
        }
    }
    QHandlerMessage *obtainMessage(int what = -1);
    void sendMessage(QHandlerMessage *message);

    virtual void handleMessage(QHandlerMessage *message) = 0;

public slots:
    void onMessage(QHandlerMessage*);


signals:
    void sendMessage_signal(QHandlerMessage *message);

private:
    QThread mWorker;  // 处理消息的后台线程
};



struct QHandlerMessage
{
    QHandlerMessage(QHandler *handler) { this->handler = handler; }
    void sendToTarget() { if (handler) handler->sendMessage(this); }

    void *obj;
    int what;
    int arg1;
    int arg2;
    int arg3;
    QMap<QString, QVariant> args;
    QHandler *handler;
};

#endif // QHANDLER_H
